<!--企业审核界面-->
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useAdminStore } from '../../store/admin'
import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElTag,
  ElMessage,
  ElDialog,
  ElDescriptions,
  ElDescriptionsItem,
  ElPagination,
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElRow,
  ElCol
} from 'element-plus'
import { useRouter } from 'vue-router'
import { computed} from "vue";

const adminStore = useAdminStore()
const router = useRouter()

// 状态定义
const companies = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const editDialogVisible = ref(false)
const selectedCompany = ref({})
const currentCompanyId = ref(null)
const rejectReason = ref('')
const isEdit = ref(false)

// 分页参数
const pagination = reactive({
  currentPage: 0,
  pageSize: 10,
  total: 0
})

// 企业表单数据
const companyForm = reactive({
  name: '',
  unifiedCode: '',
  legalPerson: '',
  registeredCapital: null,
  establishmentDate: '',
  businessScope: '',
  address: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  website: '',
  introduction: '',
  logo: ''
})

// 获取企业列表
const fetchCompanies = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,  // 直接使用当前页码
      size: pagination.pageSize
    }
    const response = await adminStore.fetchCompanies(params)
    companies.value = response.content || response.data || []
    pagination.total = response.totalElements || response.total || 0
    // 不再修改 currentPage，保持原有值
  } catch (error) {
    ElMessage.error('获取企业列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 计算属性用于处理页码
const displayCurrentPage = computed({
  get: () => pagination.currentPage + 1,  // 后端页码加1显示在前端
  set: (value) => {
    pagination.currentPage = value - 1  // 前端页码减1传给后端
  }
})

// 查看企业详情
const viewCompanyDetail = async (company) => {
  try {
    const response = await adminStore.getUserDetail(company.userId || company.id)
    selectedCompany.value = response.detail || response.data || response
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取企业详情失败: ' + error.message)
  }
}

// 显示拒绝对话框
const showRejectDialog = (companyId) => {
  currentCompanyId.value = companyId
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

// 确认拒绝
const confirmReject = async () => {
  try {
    await adminStore.reviewCompany(currentCompanyId.value, {
      status: 2,
      rejectReason: rejectReason.value
    })
    ElMessage.success('已拒绝企业申请')
    rejectDialogVisible.value = false
    fetchCompanies()
  } catch (error) {
    ElMessage.error('拒绝操作失败: ' + error.message)
  }
}

// 审核企业
const handleReview = async (companyId, status) => {
  try {
    await adminStore.reviewCompany(companyId, {
      status,
      rejectReason: ''
    })
    ElMessage.success(status === 1 ? '审核通过' : '审核拒绝')
    fetchCompanies()
  } catch (error) {
    ElMessage.error('审核操作失败: ' + error.message)
  }
}

// 编辑企业
const editCompany = (company) => {
  isEdit.value = true
  currentCompanyId.value = company.id

  // 填充表单数据
  Object.keys(companyForm).forEach(key => {
    companyForm[key] = company[key] || (key === 'registeredCapital' ? 0 : '')
  })

  editDialogVisible.value = true
}

// 保存企业信息
const saveCompany = async () => {
  try {
    if (isEdit.value) {
      await adminStore.updateCompany(selectedCompany.value.userId || currentCompanyId.value, companyForm)
      ElMessage.success('企业信息更新成功')
    } else {
      // 如果是新增功能，可以在这里实现
      ElMessage.info('新增功能尚未实现')
    }
    editDialogVisible.value = false
    fetchCompanies()
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.status === 0) {
    return 'pending-row'
  }
  return ''
}

// 获取企业状态标签类型
const getCompanyStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待审核
    case 1: return 'success'  // 已通过
    case 2: return 'danger'   // 已拒绝
    default: return ''
  }
}

// 获取企业状态标签文本
const getCompanyStatusLabel = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 格式化货币显示
const formatCurrency = (value) => {
  if (!value) return '0.00'
  return parseFloat(value).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 分页事件处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 0  // 后端页码重置为0
  fetchCompanies()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val - 1  // 前端显示页码减1后传给后端
  fetchCompanies()
}

// 初始化加载
onMounted(() => {
  fetchCompanies()
})
</script>

<template>
  <div class="company-management">
    <div class="header">
      <h2>企业管理</h2>
      <el-button @click="$router.back()" style="margin-left: auto;">返回上级</el-button>
    </div>

    <!-- 企业列表 -->
    <el-table
        :data="companies"
        v-loading="loading"
        style="width: 100%"
        :row-class-name="tableRowClassName"
    >
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="name" label="企业名称" min-width="150" />
      <el-table-column prop="unifiedCode" label="统一社会信用代码" min-width="180" />
      <el-table-column prop="legalPerson" label="法人代表" width="100" />
      <el-table-column prop="registeredCapital" label="注册资本(元)" width="120">
        <template #default="scope">
          {{ formatCurrency(scope.row.registeredCapital) }}
        </template>
      </el-table-column>
      <el-table-column prop="contactPerson" label="联系人" width="100" />
      <el-table-column prop="contactPhone" label="联系电话" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getCompanyStatusType(scope.row.status)">
            {{ getCompanyStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="viewCompanyDetail(scope.row)">
            查看详情
          </el-button>
          <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="success"
              @click="handleReview(scope.row.id, 1)"
          >
            通过
          </el-button>
          <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="danger"
              @click="showRejectDialog(scope.row.id)"
          >
            拒绝
          </el-button>
          <el-button
              size="small"
              type="primary"
              @click="editCompany(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="displayCurrentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"    style="margin-top: 20px; justify-content: center;"
    />

    <!-- 企业详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="企业详情" width="700px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="企业名称">
          {{ selectedCompany.name }}
        </el-descriptions-item>
        <el-descriptions-item label="统一社会信用代码">
          {{ selectedCompany.unifiedCode }}
        </el-descriptions-item>
        <el-descriptions-item label="法人代表">
          {{ selectedCompany.legalPerson }}
        </el-descriptions-item>
        <el-descriptions-item label="注册资本">
          {{ formatCurrency(selectedCompany.registeredCapital) }} 元
        </el-descriptions-item>
        <el-descriptions-item label="成立日期">
          {{ selectedCompany.establishmentDate }}
        </el-descriptions-item>
        <el-descriptions-item label="经营范围">
          {{ selectedCompany.businessScope }}
        </el-descriptions-item>
        <el-descriptions-item label="企业地址">
          {{ selectedCompany.address }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人">
          {{ selectedCompany.contactPerson }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ selectedCompany.contactPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="联系邮箱">
          {{ selectedCompany.contactEmail }}
        </el-descriptions-item>
        <el-descriptions-item label="企业官网">
          {{ selectedCompany.website }}
        </el-descriptions-item>
        <el-descriptions-item label="企业简介">
          {{ selectedCompany.introduction }}
        </el-descriptions-item>
        <el-descriptions-item label="Logo">
          <img
              v-if="selectedCompany.logo"
              :src="selectedCompany.logo"
              alt="企业Logo"
              style="max-width: 200px; max-height: 100px;"
          />
          <span v-else>无</span>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 拒绝理由对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝申请" width="500px">
      <el-form>
        <el-form-item label="拒绝理由">
          <el-input
              v-model="rejectReason"
              type="textarea"
              placeholder="请输入拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">确定拒绝</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑企业对话框 -->
    <el-dialog v-model="editDialogVisible" :title="isEdit ? '编辑企业' : '新增企业'" width="700px">
      <el-form :model="companyForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="企业名称">
              <el-input v-model="companyForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一信用代码">
              <el-input v-model="companyForm.unifiedCode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="法人代表">
              <el-input v-model="companyForm.legalPerson" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册资本(元)">
              <el-input v-model.number="companyForm.registeredCapital" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期">
              <el-date-picker
                  v-model="companyForm.establishmentDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="companyForm.contactPerson" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="companyForm.contactPhone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱">
              <el-input v-model="companyForm.contactEmail" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="企业官网">
          <el-input v-model="companyForm.website" />
        </el-form-item>

        <el-form-item label="企业地址">
          <el-input v-model="companyForm.address" />
        </el-form-item>

        <el-form-item label="经营范围">
          <el-input v-model="companyForm.businessScope" type="textarea" />
        </el-form-item>

        <el-form-item label="企业简介">
          <el-input v-model="companyForm.introduction" type="textarea" />
        </el-form-item>

        <el-form-item label="Logo URL">
          <el-input v-model="companyForm.logo" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCompany">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.company-management {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.pending-row) {
  background-color: #fff8e1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
